﻿using Volo.Abp.Authorization.Permissions;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Users;
using YAPACS.Organizations;

namespace YAPACS.RisServer.Authorization;

[Dependency(ReplaceServices = true)]
public class CustomPermissionStore : IPermissionStore, ISingletonDependency
{
    private readonly IRepository<ApplicationUser, Guid> _userRepository;
    private readonly ICurrentUser _currentUser;

    public CustomPermissionStore(
        IRepository<ApplicationUser, Guid> userRepository,
        ICurrentUser currentUser)
    {
        _userRepository = userRepository;
        _currentUser = currentUser;
    }

    public async Task<bool> IsGrantedAsync(string name, string providerName, string providerKey)
    {
        if (_currentUser.Id.HasValue)
        {
            var user = await _userRepository.GetAsync(_currentUser.Id.Value);
            if (user.GetUserPermissions().Any(p => p.Name == name))
            {
                return true;
            }
        }
        return false;
    }

    public async Task<MultiplePermissionGrantResult> IsGrantedAsync(string[] names, string providerName, string providerKey)
    {
        var grantResult = new MultiplePermissionGrantResult(names);

        foreach (var name in names)
        {
            if (await IsGrantedAsync(name, providerName, providerKey))
            {
                grantResult.Result[name] = PermissionGrantResult.Granted;
            }
            else
            {
                grantResult.Result[name] = PermissionGrantResult.Prohibited;
            }
        }

        return grantResult;
    }
}
